package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"user-srv/basic/golbal"
	"user-srv/basic/inits"
	"user-srv/handler/request"
	"user-srv/pkg"
)

func SendSms(c *gin.Context) {
	send := request.Sms{}
	if err := c.ShouldBind(&send); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	code := rand.Intn(9000) + 1000

	sprintf := fmt.Sprintf("%v:短信", send.Mobile)
	golbal.Rdb.Set(inits.Ctx, sprintf, code, time.Minute*5)
	sms, err := pkg.SendSms(send.Mobile, strconv.Itoa(code))
	if err != nil {
		return
	}

	if *sms.Body.Code != "OK" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  *sms.Body.Message,
		})
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "短信发送成功",
	})
}
